#!/usr/bin/env python3
from datetime import datetime, timedelta
from dateutil import parser
import pandas as pd

CHOSEN_INDEXES = ["000852.SH", "000906.SH"]
INVALID_STOCKS = ["688520.SH", "601111.SH", "300498.SZ"]
DEFAULT_DATA_PATH = './Data/'
DEFAULT_SILVER_FILE = './silver.h5'
DEFAULT_GOLD_FILE = './gold.h5'
DEFAULT_START_DATE = '20111031'
DEFAULT_END_DATE = '20210930'
MAX_END_DATE = '22620411'

CLEANSE_RATIO = [0.85, 0.70]

# CS means cross section
CS_TTM_ROE_DATE_COL = "I_RPT_PERIOD"
CS_TTM_ROE_DATE_COL2 = "I_RPT_PERIOD2"
# CS_TTM_ROE_DATE_COL = "E_RPT_PERIOD"
# CS_TTM_ROE_DATE_COL2 = "E_RPT_PERIOD2"
# CS_TTM_ROE_DATE_COL = "SEL_ANNDT"
# CS_TTM_ROE_DATE_COL2 = "SEL_ANNDT2"


def PrevQuarter(q):
    if q == '0331': return str('1231')
    elif q == '0630': return str('0331')
    elif q == '0930': return str('0630')
    elif q == '1231': return str('0930')
    else:
        raise Exception('Invalid Input: Quater must be 0331, 0630, 0930 or 1231')

def PrevYear(y):
    return str(int(y) - 1)

def PrevReportPeriod(p):
    y = p[0:4]
    q = p[4:8]
    if q == '0331':
        return PrevYear(y) + PrevQuarter(q)
    else:
        return y + PrevQuarter(p[4:8])

def SamePeriodLastYear(p):
    return str(int(p)-10000)

def LastDateOfMonth(d):
    some_date = parser.parse(d) if isinstance(d, str) else d
    # getting next month
    # using replace to get to last day + offset
    # to reach next month
    nxt_mnth = some_date.replace(day=28) + timedelta(days=4)
    # subtracting the days from next month date to
    # get last date of current Month
    return nxt_mnth - timedelta(days=nxt_mnth.day)

def LastDateOfNextMon(d):
    some_date = parser.parse(d) if isinstance(d, str) else d
    nxt_mnth = some_date.replace(day=28) + timedelta(days=4)
    return LastDateOfMonth(nxt_mnth)

def LastDateOfNextMonStr(d):
    return LastDateOfNextMon(d).strftime('%Y%m%d')

def LastDateOfMonthStr(d):
    return LastDateOfMonth(d).strftime('%Y%m%d')
